package gengine.common.console;

import gengine.clientside.ClientApplication;
import gengine.common.packets.BasePacket;
import gengine.common.packets.MessagePacket;
import gengine.common.packets.PacketProcessor;
import gengine.common.packets.PacketTypeEnum;
import gengine.common.packets.server.InitPacket;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * User: arseniy
 * Date: 22/12/11
 */
public class ConsolePanel extends JPanel implements KeyListener {
    private JScrollPane scrollPane;
    private JTextField commandField;
    private JTextArea textArea;
    private BaseConsole console;

    public ConsolePanel(BaseConsole console,PacketProcessor cpp) {
        this();
        this.console = console;
        ClientApplication app = ClientApplication.getApplication();
        app.Subscribe(cpp, PacketTypeEnum.Message);
        app.Subscribe(cpp, PacketTypeEnum.ServerInitPacket);
        app.Subscribe(cpp, PacketTypeEnum.ClientInfoPacket);
    }

    protected ConsolePanel() {
        super(new BorderLayout());
        textArea = new JTextArea(5, 50);
        textArea.setName("textArea");
        textArea.setText("Welcome!\n");
        textArea.setEditable(false);
        scrollPane = new JScrollPane(textArea);
        scrollPane.setName("scrollPane");
        add(scrollPane, BorderLayout.CENTER);
        commandField = new JTextField();
        commandField.addKeyListener(this);
        add(commandField, BorderLayout.PAGE_END);
        setPreferredSize(new Dimension(800, 300));
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_ENTER:
                textArea.append(console.processCommand(commandField.getText()));
                commandField.setText("");
                break;
            case KeyEvent.VK_UP:
                commandField.setText(console.scrollUp());
                break;
            case KeyEvent.VK_DOWN:
                commandField.setText(console.scrollDown());
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    public void addMessage(String s) {
        textArea.append(String.format("[%s] %s \n", SimpleDateFormat.getTimeInstance().format(new Date()), s));
    }
}
